package org.hypnus.e.util;

/**
 * @author hypnus
 * 
 */
public abstract class ByteUtil {

	/**
	 * 
	 * @param left
	 * @param right
	 * @return
	 */
	public static byte[] join(byte[] left,int leftLen, byte[] right, int rightLen) {
		byte[] dest = null;
		if(left == null && right == null){
			return dest ;
		}
		if (left == null) {
			dest = new byte[rightLen];
			System.arraycopy(right, 0, dest, 0, rightLen);
		} else if(right == null){
			dest = new byte[leftLen];
			System.arraycopy(left, 0, dest, 0, leftLen);
		}else{
			dest = new byte[leftLen + rightLen];
			System.arraycopy(left, 0, dest, 0, leftLen);
			System.arraycopy(right, 0, dest, leftLen, rightLen);
		}
		
		return dest;
	}

	/**
	 * 
	 * @param src
	 * @param target
	 * @return
	 */
	public static int indexOf(byte[] src, byte[] target) {
		int pos = -1;
		if (src != null && src.length > 0 && target != null && target.length > 0) {
			for (int i = 0; i < src.length; i++) {
				if (src[i] == target[0]) {
					pos = i;
					for (int j = 1; j < target.length; j++) {
						if (src[i + j] != target[j]) {
							pos = -1;
							break;
						}
					}
					if (pos >= 0) {
						break;
					}
				}
			}
		}
		return pos;
	}

	/**
	 * 
	 * @param src
	 * @param pos
	 * @param length
	 * @return
	 */
	public static byte[] subSeq(byte[] src, int pos, int length) {
		byte[] result = null;
		if (src != null) {
			if (length > src.length) {
				throw new IllegalArgumentException("the argument of 'length' is large than the array of byte[] src...");
			} else if (pos < 0 || pos > src.length - 1) {
				throw new IllegalArgumentException("the argument of 'pos' is illegal...");
			} else {
				result = new byte[length];
				for (int i = pos; i < pos + length; i++) {
					result[i - pos] = src[i];
				}
			}
		}
		return result;
	}

	public static void main(String[] args) {
		// long start = System.currentTimeMillis();
		// for (int i = 0; i < 10000; i++) {
		// String str1 =
		// "Hello0000000000000000000000000000000000000000000000000000000000                                                                                                                                                                                       ";
		// String str2 =
		// "World0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
		//
		// byte[] rs = ByteUtil.join(null, str2.getBytes());
		// // System.out.println(new String(rs));
		// }
		// System.out.println(System.currentTimeMillis() - start);

		String str1 = "Hello World welcome to china ...........";
		String str2 = "come";
		System.out.println(ByteUtil.indexOf(str1.getBytes(), str2.getBytes()));
		System.out.println(ByteUtil.indexOf(str1.getBytes(), "".getBytes()));

	}
}
